/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */
package com.ecarx.systemui.plugin.model

import android.car.Car
import android.car.hardware.property.CarPropertyManager
import android.content.Context
import com.ecarx.systemui.plugin.PluginContext
import com.ecarx.systemui.plugin.utils.LogUtils
import com.ecarx.xui.adaptapi.car.IWrapper
import kotlinx.coroutines.delay

abstract class BaseModel {

    companion object {
        private const val TAG = "BaseModel"
    }

    private lateinit var mContext: Context

    private var mCar: Car? = null

    @Volatile
    private var mIsConnectedToCar = false

    lateinit var carPropertyManager: CarPropertyManager
    lateinit var wrapper: IWrapper

    init {
        LogUtils.d(TAG, "BaseModel init")
        baseInit()
    }


    private fun baseInit() {
        mContext = PluginContext.getInstance().pluginContext
        wrapper = com.ecarx.xui.adaptapi.car.Car.createWrapper(mContext)

        if (mCar == null || !mCar!!.isConnected) {
            mCar = Car.createCar(
                mContext, null, Car.CAR_WAIT_TIMEOUT_DO_NOT_WAIT
            ) { car: Car, ready: Boolean ->
                LogUtils.d(TAG, "createCar, ready:$ready")
                mCar = car
                if (ready) {
                    LogUtils.d(TAG, "onConnected.")
                    mIsConnectedToCar = true
                    carPropertyManager =
                        car.getCarManager(Car.PROPERTY_SERVICE) as CarPropertyManager
                }
            }
        }
    }


    suspend fun waitUntilReady() {
        if (mIsConnectedToCar) {
            LogUtils.d(TAG, "already connected to car.")
            return
        }

        val start = System.currentTimeMillis()
        while (!mIsConnectedToCar) {
            val now = System.currentTimeMillis()
            if (now - start > 1000) {
                LogUtils.e("connect car service timeout !")
                break
            }
            delay(10)
            LogUtils.d("connect car service try again !")
        }
    }

}